<template>
  <div class="supplier-reconciliation">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 日期范围 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-26')]"
        />
      </el-form-item>

      <!-- 供应商选择（弹窗） -->
      <el-form-item label="供应商">
        <el-button type="primary" @click="openDialog('supplier')">
          {{
            selectedSupplier.name
              ? `${selectedSupplier.code} ${selectedSupplier.name}`
              : "(请选择供应商)"
          }}
        </el-button>
      </el-form-item>

      <!-- 显示商品明细 -->
      <el-form-item>
        <el-checkbox v-model="filter.showGoodsDetail">显示商品明细</el-checkbox>
      </el-form-item>

      <!-- 查询按钮 -->
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 供应商选择弹窗 ========== -->
    <el-dialog
      title="选择供应商"
      v-model="dialogs.supplier.visible"
      width="860px"
    >
      <div class="dialog-header">
        <!-- 类别筛选（树形结构） -->
        <el-tree
          ref="categoryTreeRef"
          :data="categoryTree"
          show-checkbox
          node-key="id"
          :props="{ label: 'label', children: 'children' }"
          default-expand-all
          style="width: 220px; margin-right: 24px"
        />

        <!-- 搜索框 -->
        <el-input
          v-model="dialogs.supplier.keyword"
          placeholder="输入编号/名称/联系人/电话查询"
          clearable
          style="width: 240px"
        />

        <!-- 显示禁用供应商 -->
        <el-checkbox v-model="dialogs.supplier.showDisabled" class="ml-4"
          >显示禁用供应商</el-checkbox
        >

        <!-- 查询按钮 -->
        <el-button type="primary" class="ml-4" @click="fetchSuppliers"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.supplier.list"
        :row-key="(row) => row.id"
        @selection-change="handleSupplierSelect"
        border
        style="width: 100%; margin-top: 16px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="category" label="类别" min-width="100" />
        <el-table-column prop="code" label="编号" min-width="120" sortable />
        <el-table-column prop="name" label="名称" min-width="180" sortable />
        <el-table-column prop="contact" label="联系人" min-width="100" />
        <el-table-column prop="phone" label="手机" min-width="140" />
        <el-table-column prop="remark" label="备注" min-width="120" />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.supplier.limit = val)"
        @current-change="(val) => (dialogs.supplier.page = val)"
        :current-page="dialogs.supplier.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.supplier.limit"
        :total="dialogs.supplier.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.supplier.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSupplierSelection"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 对账表展示 ========== -->
    <!-- 空状态（未选供应商或无数据） -->
    <div
      class="empty-state"
      v-if="!selectedSupplier.name || tableData.length === 0"
    >
      <i class="el-icon-document" style="font-size: 48px; color: #dcdcdc"></i>
      <p>暂无内容，点击查询试试吧</p>
    </div>

    <!-- 对账表（已选供应商且有数据） -->
    <div v-else class="statement-container">
      <div class="statement-header">
        <h3>云进销存体验账套</h3>
        <h4>供应商对账单</h4>
        <p>供应商：{{ selectedSupplier.name }}</p>
        <p>联系人：{{ selectedSupplier.contact }}</p>
        <p>电话：{{ selectedSupplier.phone }}</p>
        <p>地址：{{ selectedSupplier.address }}</p>
        <p>日期：{{ filter.dateRange[0] }} 至 {{ filter.dateRange[1] }}</p>
      </div>

      <el-table
        :data="tableData"
        border
        show-summary
        :summary-method="generateSummary"
        :header-cell-style="{ background: '#F8F9FA' }"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column
          prop="billDate"
          label="单据日期"
          min-width="120"
          sortable
        />
        <el-table-column
          prop="billNo"
          label="单据编号"
          min-width="120"
          sortable
        />
        <el-table-column prop="businessType" label="业务类别" min-width="100" />
        <el-table-column
          prop="purchaseAmount"
          label="采购金额"
          align="right"
          min-width="120"
          v-if="filter.showGoodsDetail"
        />
        <el-table-column
          prop="discountAmount"
          label="优惠金额"
          align="right"
          min-width="120"
          v-if="filter.showGoodsDetail"
        />
        <el-table-column
          prop="payableAmount"
          label="应付金额"
          align="right"
          min-width="120"
        />
        <el-table-column
          prop="actualPayment"
          label="实际付款金额"
          align="right"
          min-width="120"
        />
        <el-table-column
          prop="payableBalance"
          label="应付款余额"
          align="right"
          min-width="120"
          sortable
        />
        <el-table-column prop="remark" label="备注" min-width="120" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// ========== 关键修复：顶层 ref 绑定树形组件 ==========
const categoryTreeRef = ref(null);

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  selectedSupplier: null, // 选中的供应商对象
  showGoodsDetail: false, // 显示商品明细
});

// ========== 选中供应商回显 ==========
const selectedSupplier = ref({
  name: "",
  code: "",
  contact: "",
  phone: "",
  address: "",
});

// ========== 对话框状态 ==========
const dialogs = reactive({
  supplier: {
    visible: false,
    keyword: "", // 搜索关键词
    showDisabled: false, // 显示禁用供应商
    list: [], // 供应商列表
    page: 1, // 分页页码
    limit: 10, // 分页大小
    total: 0, // 总条数
    selected: [], // 选中的供应商（多选，实际业务通常单选）
  },
});

// ========== 基础数据模拟 ==========
// 供应商类别树（树形结构）
const categoryTree = ref([
  {
    id: 1,
    label: "广东",
    children: [
      { id: 11, label: "海鲜供应商" },
      { id: 12, label: "酒水饮料供应商" },
      { id: 13, label: "食品供应商" },
    ],
  },
  {
    id: 2,
    label: "湖南",
    children: [
      { id: 21, label: "辣条供应商" },
      { id: 22, label: "零食供应商" },
    ],
  },
]);

// 模拟供应商列表（与界面数据一致）
const mockSuppliers = [
  {
    id: 1,
    code: "G00001",
    name: "商品综合批发有限公司",
    category: "广东", // 匹配类别树的“广东”
    contact: "王",
    phone: "18000000000",
    address: "广东省广州市天河区百合路",
    initialPayable: 13881.78,
    disabled: false,
  },
  {
    id: 2,
    code: "G00002",
    name: "金小蝶食品贸易有限公司",
    category: "酒水饮料供应商", // 匹配类别树的“广东→酒水饮料供应商”
    contact: "管先生",
    phone: "18877777777",
    address: "广东省深圳市南山区",
    initialPayable: 16446.44,
    disabled: false,
  },
  {
    id: 3,
    code: "G00003",
    name: "广州食品批发有限公司",
    category: "食品供应商", // 匹配类别树的“广东→食品供应商”
    contact: "小裴",
    phone: "18048444844",
    address: "广东省广州市越秀区",
    initialPayable: 9555.65,
    disabled: false,
  },
  {
    id: 4,
    code: "G00004",
    name: "深圳食品加工有限公司",
    category: "食品供应商", // 匹配类别树的“广东→食品供应商”
    contact: "樊樊",
    phone: "18055555555",
    address: "广东省深圳市福田区",
    initialPayable: 7234.56,
    disabled: true, // 禁用状态
  },
  {
    id: 5,
    code: "G00005",
    name: "食品零售供应商",
    category: "广东", // 匹配类别树的“广东”
    contact: "李先生",
    phone: "18323122312",
    address: "广东省广州市海珠区",
    initialPayable: 0,
    disabled: false,
  },
  {
    id: 6,
    code: "G00006",
    name: "零食供应商",
    category: "零食供应商", // 匹配类别树的“湖南→零食供应商”
    contact: "",
    phone: "18066666666",
    address: "湖南省长沙市",
    initialPayable: 11223.34,
    disabled: false,
  },
  {
    id: 7,
    code: "G00007",
    name: "测试供应商",
    category: "海鲜供应商", // 匹配类别树的“广东→海鲜供应商”
    contact: "",
    phone: "18077777777",
    address: "广东省珠海市",
    initialPayable: 0,
    disabled: false,
  },
  {
    id: 8,
    code: "G00008",
    name: "测试",
    category: "", // 无类别
    contact: "",
    phone: "18088888888",
    address: "测试地址",
    initialPayable: 0,
    disabled: false,
  },
  {
    id: 9,
    code: "G00009",
    name: "测试111",
    category: "", // 无类别
    contact: "测试",
    phone: "18099999999",
    address: "测试地址",
    initialPayable: 0,
    disabled: false,
  },
];

// 模拟对账数据（以 G00001 供应商为例）
const mockReconciliationData = [
  {
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    purchaseAmount: 0,
    discountAmount: 0,
    payableAmount: 0,
    actualPayment: 0,
    payableBalance: 13881.78,
    remark: "",
  },
  // 可扩展交易数据...
];

// ========== 对话框交互逻辑 ==========
/** 打开供应商选择弹窗 */
const openDialog = (type) => {
  if (type === "supplier") {
    dialogs.supplier.visible = true;
    fetchSuppliers(); // 初始化加载供应商
  }
};

/** 获取供应商列表（筛选+分页） */
const fetchSuppliers = () => {
  const { keyword, showDisabled, page, limit } = dialogs.supplier;

  // 从顶层 ref 获取树形组件选中节点（含子节点）
  const checkedNodes = categoryTreeRef.value?.getCheckedNodes() || [];
  const selectedCategories = checkedNodes.map((node) => node.label);

  // 筛选逻辑
  let filtered = mockSuppliers.filter((item) => {
    // 类别筛选：供应商类别必须在选中的类别中（含子节点）
    if (
      selectedCategories.length > 0 &&
      !selectedCategories.includes(item.category)
    ) {
      return false;
    }
    // 搜索筛选
    if (keyword) {
      return (
        item.code.includes(keyword) ||
        item.name.includes(keyword) ||
        item.contact.includes(keyword) ||
        item.phone.includes(keyword)
      );
    }
    return true;
  });

  // 禁用筛选
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled);
  }

  // 分页处理
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.supplier.list = filtered.slice(start, end);
  dialogs.supplier.total = filtered.length;
};

/** 供应商表格多选事件 */
const handleSupplierSelect = (val) => {
  dialogs.supplier.selected = val;
};

/** 确认选择供应商（单选处理） */
const confirmSupplierSelection = () => {
  if (dialogs.supplier.selected.length === 0) {
    ElMessage.warning("请选择供应商");
    return;
  }
  // 业务场景通常为单选，取第一个选中项
  const supplier = dialogs.supplier.selected[0];
  selectedSupplier.value = {
    name: supplier.name,
    code: supplier.code,
    contact: supplier.contact,
    phone: supplier.phone,
    address: supplier.address,
  };
  filter.selectedSupplier = supplier; // 保存选中的供应商
  dialogs.supplier.visible = false;
  ElMessage.success("供应商选择成功！");
};

// ========== 数据查询逻辑 ==========
const tableData = ref([]);

/** 查询对账数据 */
const queryData = () => {
  if (!filter.selectedSupplier) {
    ElMessage.warning("请先选择供应商！");
    tableData.value = [];
    return;
  }
  // 模拟根据供应商查询数据（此处直接用mock数据）
  tableData.value = mockReconciliationData;
};

/** 合计行计算（应付款余额） */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计:";
      return;
    }
    if (column.prop === "payableBalance") {
      const total = data.reduce((acc, item) => acc + item.payableBalance, 0);
      sums[index] = total.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// ========== 初始化 ==========
onMounted(() => {
  tableData.value = []; // 初始无数据
});
</script>

<style scoped>
.supplier-reconciliation {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #999;
}

.statement-container {
  margin-top: 20px;
}

.statement-header {
  margin-bottom: 12px;
}

.statement-header h3,
.statement-header h4 {
  margin: 4px 0;
  font-weight: 600;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>